package wt

import (
	"context"
	"fmt"
	"sync/atomic"

	"gitee.com/AlexWoo/arpc/alog"
	"gitee.com/AlexWoo/arpc/anet"
	"github.com/quic-go/webtransport-go"
)

var (
	cid uint64
)

type Connection struct {
	conn   *webtransport.Session
	id     uint64
	closed uint32

	h anet.Handler

	lctx   *alog.LogCtx
	remote string
	local  string

	// for client
	isClient         bool
	retryIntervalSec uint32
	onConnect        anet.OnConnect
	onDisconnect     anet.OnDisconnect
}

func newConnection(conf *alog.LogConf) *Connection {
	c := &Connection{
		conn:             nil,
		id:               atomic.AddUint64(&cid, 1),
		closed:           0,
		isClient:         false,
		retryIntervalSec: 0,
	}

	c.lctx = &alog.LogCtx{
		Prefix:   c.Prefix,
		Suffix:   c.Suffix,
		LogLevel: alog.Level[conf.LogLevel],
	}

	return c
}

func (c *Connection) loop() {
	defer func() {
		if c.closed != 1 {
			c.Close()
		}

		c.conn = nil
	}()

	for {
		data, err := c.conn.ReceiveDatagram(context.Background())
		if err != nil {
			alog.LogError(c.lctx, "receive datagram error: %v", err)
			return
		}

		c.h.OnMsg(c, data)
	}
}

func (c *Connection) Send(bts []byte) error {
	if c.conn == nil {
		err := fmt.Errorf("send message: %s bug connection is closed", string(bts))
		alog.LogError(c.lctx, err.Error())
		return err
	}

	err := c.conn.SendDatagram(bts)
	if err != nil {
		alog.LogError(c.lctx, "send error: %v", err)
	}

	return err
}

func (c *Connection) Close() {
	closed := atomic.SwapUint32(&c.closed, 1)
	if closed == 1 {
		return
	}

	c.conn.CloseWithError(webtransport.SessionErrorCode(anet.OK), "close")
}

func (c *Connection) Lctx() *alog.LogCtx {
	return c.lctx
}

func (c *Connection) Prefix() string {
	return fmt.Sprintf("*%d", c.id)
}

func (c *Connection) Suffix() string {
	if c.conn != nil {
		return fmt.Sprintf("remote: %s, local: %s", c.remote, c.local)
	}

	return ""
}
